<?php

namespace  Smallsha\Classes;

class WangSu
{
    const ACCESS_KEY = '';
    const ACCESSKEYSECRET = '';
    const REQUEST_URL = "https://sms.server.matocloud.com/sms/is/api/sms/simple/sendSms";

    public function send_post($url, $head, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 7);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $server_output = curl_exec($ch);
        if (curl_error($ch)) {
            curl_close($ch);
            return false;
        }
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $http_code_int = intval($http_code);
        if ($http_code_int === 200) { // 只接收 200 返回的数据
            return $server_output;
        }
        echo 'http_code_error:' . $url . '|http_code:' . $http_code_int;
        return null;
    }

    public function arrToString($arr_data)
    {
        $str = '';
        foreach ($arr_data as $key => $val) {
            if (empty($val)) {
                $val = "";
            }
            $str .= "&" . $key . "=" . $val;
        }
        $str = substr($str, 1);
        return $str;
    }


    public function sendSms($phone, $content = "【 网 宿 科 技 】 您 的 验 证 码 为123456")
    {
        $cur_time = date('YmdHis', time());
        $sms_data = "{\"type\":2,\"content\":\"$content \",\"phone\":\"$phone\"}";
        $sign_arr = array(
            'auth-accessKey' => self::ACCESS_KEY,
            'auth-timeStamp' => $cur_time,
            'sms' => $sms_data,
        );
        $sign_str = $this->arrToString($sign_arr);
        $sign_str = $sign_str . "&accessKeySecret=" . self::ACCESSKEYSECRET;
        $sign = strtolower(md5($sign_str));
        $head_data = array(
            'auth-timeStamp:' . $cur_time,
            'auth-accessKey:' . self::ACCESS_KEY,
            'Content-Type:application/x-www-form-urlencoded',
            'auth-signature:' . $sign
        );
        $data = array(
            'sms' => $sms_data,
        );
        $postData = http_build_query($data);
        $res = $this->send_post(self::REQUEST_URL, $head_data, $postData);
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }
}


